<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryParamsRef" :inline="true" label-width="100">
      <el-form-item label="商户号" prop="merchantNoList" v-hasPermi="[9]">
        <el-select class="w-195" multiple v-model="queryParams.merchantNoList" placeholder="请选择" clearable
          @change="getPaymentData">
          <el-option v-for="item in merchantListData" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-hasPermi="[9]" label="商户订单号" prop="uniNo">
        <el-input v-model="queryParams.uniNo" clearable placeholder="请输入商户订单号" style="width: 240px" />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" clearable placeholder="请输入订单编号" style="width: 240px" />
      </el-form-item>
      <el-form-item label="三方备注" prop="utr">
        <el-input v-model="queryParams.utr" clearable placeholder="请输入utr" style="width: 240px" />
      </el-form-item>
      <!--      <el-form-item label="三方单号" prop="utrNo">-->
      <!--        <el-input v-model="queryParams.utrNo" clearable placeholder="请输入三方单号" style="width: 240px"/>-->
      <!--      </el-form-item>-->
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" class="w-195" clearable placeholder="请选择" style="width: 240px">
          <el-option key="0" label="未支付" value="1" />
          <el-option key="1" label="已支付" value="2" />
          <el-option key="2" label="已拒绝" value="3" />
        </el-select>
      </el-form-item>
          <!-- <el-form-item label="订单开始时间" prop="startDate">
            <el-date-picker v-model="queryParams.startDate" placeholder="请选择申请开始时间" type="date" />
          </el-form-item>
          <el-form-item label="订单结束时间" prop="endDate">
            <el-date-picker v-model="queryParams.endDate" placeholder="请选择申请结束时间" type="date" />
          </el-form-item> -->
      <el-form-item label="申请开始时间" prop="startDate">
            <el-date-picker  v-model="queryParams.startDate" placeholder="请选择申请开始时间" type="date" />
          </el-form-item>
          <el-form-item label="申请结束时间" prop="endDate">
            <el-date-picker  v-model="queryParams.endDate" placeholder="请选择申请结束时间" type="date" />
          </el-form-item>
      <!--<el-form-item label="客户银行卡号" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="客户手机号" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入手机号"
          clearable
        />
      </el-form-item> -->
      <!-- <el-form-item label="客户名" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入客户名"
          clearable
        />
      </el-form-item>
      <el-form-item label="交易成功时间" prop="status">
        <el-col :span="10">
          <el-form-item prop="date1">
            <el-date-picker
              type="date"
              aria-label="Pick a date"
              placeholder="请选择交易开始时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="2">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="date2">
            <el-date-picker
              type="date"
              aria-label="Pick a date"
              placeholder="请选择交易结束时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getPaymentData">查询
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button icon="Plus" type="warning" @click="addShow">新增</el-button>
        <el-button plain type="danger" @click="batchRejection">批量拒绝</el-button>
        <el-button icon="Download" type="success" @click="exportShow = true">导出 </el-button>
        <el-button icon="Download" type="success" @click="exportHandle">导出商户数据 </el-button>
        <el-button icon="Upload" type="success" @click="importClick">导入</el-button>
        <el-button  type="warning" @click="outClick">转三方</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column align="center" label="序号" type="selection" width="55" :selectable="selectable" />
      <el-table-column align="center" label="商户号" prop="merchantNo" />
      <el-table-column label="订单编号" width="200" align="center" prop="orderNo" />
      <el-table-column v-hasPermi="[9]" align="center" label="商户订单号" prop="uniNo" />
      <el-table-column align="center" label="订单状态" prop="orderStatusName" />
      <el-table-column align="center" label="订单金额" prop="orderBalance" />
      <el-table-column align="center" label="实际金额" prop="balance" />
      <el-table-column align="center" label="手续费率(%)" prop="orderRate" />
      <el-table-column align="center" label="手续费" prop="rateBalance" />
      <el-table-column align="center" label="交易方式" prop="uniChannelName" />
      <el-table-column align="center" label="申请时间" prop="applyTime" width="150"/>
      <el-table-column align="center" label="处理时间" prop="dealTime"  width="150"/>
      <el-table-column align="center" label="utr" prop="utr" />
      <el-table-column align="center" label="导出状态" width="150">
        <template #default="scope">
          <el-button type="warning" v-show="scope.row.exportExist && scope.row.orderStatus == 1" @click="removeHandler(scope.row.outerOrderId)">移除标记
          </el-button>
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--        align="center"-->
      <!--        label="三方单号"-->
      <!--        prop="utrNo"-->
      <!--        width="150"-->
      <!--      />-->
      <!-- <el-table-column
        label="备注"
        width="200"
        align="center"
        prop="expenses"
      /> -->
      <el-table-column align="center" label="操作" width="150" v-hasPermi="[9]">
        <template #default="scope">
          <el-button size="small" type="warning" plain @click="requestHandler(scope.row)"
            v-if="scope.row.orderStatus == 1">确认
          </el-button>
          <el-button size="small" type="danger" plain @click="rejectHandler(scope.row)"
            v-if="scope.row.orderStatus == 1">拒绝
          </el-button>
          <el-button v-if="scope.row.orderStatus != 1" size="small" @click="infoHandler(scope.row)">详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getPaymentData" />
    <el-dialog v-model="detailShow" :title="title" width="50%" destroy-on-close @close="resetHandle">
      <el-form ref="formDataRef" :model="formData" label-width="150" :rules="rules">
        <el-form-item label="订单金额">
          <el-input v-model="formData.orderBalance" disabled />
        </el-form-item>
        <el-form-item label="平台流水号">
          <el-input v-model="formData.orderNo" disabled />
        </el-form-item>
        <el-form-item label="订单手续费率(%)">
          <el-input v-model="formData.orderRate" disabled />
        </el-form-item>
        <el-form-item label="订单手续费">
          <el-input v-model="formData.rateBalance" disabled />
        </el-form-item>
        <el-form-item label="渠道名称">
          <el-input v-model="formData.uniChannelName" disabled />
        </el-form-item>
        <el-form-item label="商户订单号">
          <el-input v-model="formData.uniNo" disabled />
        </el-form-item>
        <el-form-item label="utr" prop="utr">
          <el-input v-model="formData.utr" placeholder="请输入utr" :disabled="formData.orderStatus != 1" />
        </el-form-item>
        <el-form-item label="Account number">
          <el-input v-model="formData.accountNumber" disabled />
        </el-form-item>
        <el-form-item label="Bank Name">
          <el-input v-model="formData.bankName" disabled />
        </el-form-item>
        <el-form-item label="Holder Name">
          <el-input v-model="formData.holderName" disabled />
        </el-form-item>
        <el-form-item label="IFSC">
          <el-input v-model="formData.ifsc" disabled />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetHandle" v-show="formData.orderStatus == 1">取消 </el-button>
          <el-button type="warning" @click="confirmHandle" v-show="formData.orderStatus == 1">确认代付 </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="addDataShow" title="新增代付" width="50%" @close="resetHandle">
      <el-form ref="addDataRef" :model="addData" :rules="rules" label-width="150">
        <el-form-item label="Account number" prop="accountNumber">
          <el-input v-model="addData.accountNumber" placeholder="请输入Account number" />
        </el-form-item>
        <el-form-item label="Bank Name" prop="bankName">
          <el-input v-model="addData.bankName" placeholder="请输入Bank Name" />
        </el-form-item>
        <el-form-item label="Holder Name" prop="holderName">
          <el-input v-model="addData.holderName" placeholder="请输入Holder Name" />
        </el-form-item>
        <el-form-item label="IFSC" prop="ifsc">
          <el-input v-model="addData.ifsc" placeholder="请输入IFSC" />
        </el-form-item>
        <el-form-item label="订单金额" prop="orderPrice">
          <el-input v-model="addData.orderPrice" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item v-if="showUserId" label="商户编号" prop="merchantNo">
          <el-input v-model="addData.merchantNo" placeholder="商户编号" />
        </el-form-item>
        <el-form-item label="商户订单号" prop="uniNo">
          <el-input v-model="addData.uniNo" placeholder="请输入商户订单号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetHandle">取消 </el-button>
          <el-button type="warning" @click="addHandle">新增代付</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="exportShow" width="400" center @close="resetHandle">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="80">
        <el-form-item label="账户" prop="account">
          <el-input v-model="form.account" placeholder="请输入账户号" style="width: 240px" />
        </el-form-item>
        <el-form-item label="最大金额" prop="maxBalance">
          <el-input v-model="form.maxBalance" placeholder="请输入最大金额" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetHandle">取消 </el-button>
          <el-button type="warning" @click="paymentExport">确认导出</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="importShow" title="文件导入" destroy-on-close width="400" algin-center close-on-press-escape>
      <FileUpload :isShowTip="false"></FileUpload>
    </el-dialog>
  </div>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import useUserStore from "@/store/modules/user";
import {
  addPayment,
  merchantList,
  payForAnother,
  paymentData,
  refusePayment,
  bathRefusePayment,
  changeExport,
  importFile,
  transferThird
} from "@/api/deal/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { checkPermi } from "@/utils/permission.js";
import { download } from "@/utils/request.js";
import FileUpload from '@/components/FileUpload/index.vue'

const userStore = useUserStore();
const { proxy } = getCurrentInstance();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantNoList: [],
  },
  addData: {},
  formData: {},
  rules: {
    orderPrice: [
      { required: true, message: "订单价必填！", trigger: "blur" },
      {
        pattern: /^\d{1,9}$|^\d{1,9}[.]\d{1,2}$/,
        message: "金额为数字类型最长输入9位整数且最多保留两位小数",
        trigger: "blur",
      },
    ],
    merchantNo: [
      { required: true, message: "商户编号必填！", trigger: "blur" },
    ],
    utr: [{ required: true, message: "三方备注信息必填！", trigger: "blur" }],
    utrNo: [{ required: true, message: "三方单号必填！", trigger: "blur" }],
    uniNo: [{ required: true, message: "商户订单号必填！", trigger: "blur" }],
    accountNumber: [
      { required: true, message: "accountNumber必填！", trigger: "blur" },
    ],
    bankName: [{ required: true, message: "bankName必填！", trigger: "blur" }],
    holderName: [
      { required: true, message: "holderName必填！", trigger: "blur" },
    ],
    ifsc: [{ required: true, message: "ifsc必填！", trigger: "blur" }],
    account: [{ required: true, message: "导出账号必填！", trigger: "blur" }],
    maxBalance: [{ required: true, message: "最大金额必填！", trigger: "blur" }],
  },
});

const { queryParams, form, rules, formData, addData } = toRefs(data);
const merchantListData = ref([]);
const title = ref('代付确认')
function getMerchantList() {
  merchantList().then((res) => {
    merchantListData.value = res.data.map((item) => {
      return {
        value: item.merchantNo,
        label: item.merchantNo,
      };
    });
  });
}
const exportShow = ref(false)
const tableData = ref([]);
const total = ref(0);
const showUserId = computed(() => {
  return checkPermi([9]);
});

function getPaymentData() {
  paymentData(queryParams.value).then((res) => {
    const { total: totalNum, data } = res.data;
    tableData.value = data;
    total.value = totalNum;
  });
}

const detailShow = ref(false);

function requestHandler(row) {
  formData.value = row;
  detailShow.value = true;
  title.value = '代付确认'
}

// 代付确认
function confirmHandle() {
  proxy.$refs["formDataRef"].validate((valid, fields) => {
    if (valid) {
      payForAnother(formData.value).then((res) => {
        ElMessage.success("代付确认成功！");
        getPaymentData();
        resetHandle();
      });
    }
  });
}
// 拒绝代付
function rejectHandler(row) {
  ElMessageBox.confirm('是否拒绝代付？', '拒绝代付', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    refusePayment(row).then(() => {
      ElMessage.success('拒绝代付成功！')
      getPaymentData();
    })
  })
    .catch(() => {
      ElMessage.warning('取消拒绝代付！')
    })
}
const batchList = ref([])
const selectable = (row) => {
  return row.orderStatus == 1 && row.exportExist !=1
}
// 批量拒绝
function handleSelectionChange(val) {
  batchList.value = val
}
function batchRejection() {
  if (!batchList.value.length) {
    ElMessage.warning('请先勾选！')

  } else {

    bathRefusePayment({ bathList: batchList.value }).then(() => {
      ElMessage.success('批量拒绝代付成功！')
      getPaymentData()
    })
  }
}
// 转三方
function outClick(){
  if (!batchList.value.length) {
    ElMessage.warning('请先勾选！')

  } else {
    ElMessageBox.confirm('是否转三方？', '转三方', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
   const idList=batchList.value.map(item => item.outerOrderId)
      transferThird({ outerOrderIdList: idList }).then(() => {
        ElMessage.success('批量转三方成功！')
        getPaymentData()
      })
    })
      .catch(() => {
        ElMessage.warning('取消批量转三方！')
      })
  }
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryParamsRef");
  getPaymentData();
}

function resetHandle() {
  proxy.resetForm("formDataRef");
  proxy.resetForm("addDataRef");
  proxy.resetForm("formRef");
  detailShow.value = false;
  formData.value = {};
  addDataShow.value = false;
  addData.value = {};
  exportShow.value = false;
  form.value = {}
}

const addDataShow = ref(false);

function addShow() {
  addDataShow.value = true;
}
// 修改导出状态
function removeHandler(id) {
  ElMessageBox.confirm('是否移除标识？', '修改导出状态', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    changeExport({ outerOrderId: id }).then((res) => {
      ElMessage.success('修改导出状态成功！')
      getPaymentData()
    })
  })
    .catch(() => {
      ElMessage.warning('取消修改导出状态！')
    })

}
//新增代付

function addHandle() {
  proxy.$refs["addDataRef"].validate((valid, fields) => {
    if (valid) {
      addPayment(addData.value).then((res) => {
        ElMessage.success("操作成功");
        getPaymentData();
        resetHandle();
      });
    }
  });
}



// 代付详情
function infoHandler(row) {
  formData.value = row;
  detailShow.value = true;
  title.value = '代付详情'
}
// 代付导出
function generateSalaryCode() {
  const date = new Date();
  const year = date.getFullYear().toString().slice(-2); // 获取年份
  const month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份，并确保是两位数
  const day = ('0' + date.getDate()).slice(-2); // 获取日期，并确保是两位数
  const currentDate=`${year}${month}${day}`;

  // 生成一个随机六位数
  const randomNumber = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');

  // 拼接成最终的格式
  return `SALARY_${currentDate}_${randomNumber}`;
}

function paymentExport() {
  const name=generateSalaryCode()

  proxy.$refs["formRef"].validate((valid, fields) => {
    if (valid) {
      queryParams.value.sourceAccountNumber = form.value.account
      queryParams.value.maxBalance = form.value.maxBalance
      download("/manage/payment/payment/export", queryParams.value, name+`.xlsx`)
      resetHandle()
    }
  })
}
// 导出商户数据
function exportHandle() {
  const name=generateSalaryCode()
  download("/merchant/payment/payment/export", queryParams.value, name+`.xlsx`)
}
// 代付导入
// 批量代收
const importShow = ref(false)
const fileList = ref([])
const upfile = ref()
function importClick() {
  importShow.value = true
  fileList.value = []
}
function handChange(file) {
  upfile.value = file

}
function batchCollection() {
  if (!upfile.value) {
    ElMessage.warning('请先上传文件');
    return;
  }
  const formData = new FormData();
  const file = upfile.value.raw;
  const fileExtension = file.name.split('.').pop().toLowerCase();
  if (fileExtension !== 'xlsx' && fileExtension !== 'xls') {
    ElMessage.warning('文件格式错误');
    return;
  }
  formData.append('file', file);
  for (let [key, value] of formData.entries()) {
  console.log(key, value);
}
  const data = {
    file: formData
  }
  proxy.$modal.loading("正在上传文件，请稍候...");

  importFile(data).then((res) => {
    ElMessage.success('导入文件成功');
    // getList();
  }).catch((error) => {
    ElMessage.error('导入文件失败: ' + error.msg);
  }).finally(() => {
    proxy.$modal.closeLoading();
    importShow.value = false
  });
}
onMounted(() => {
  if (showUserId.value) {
    getMerchantList();
  }
  getPaymentData();
});
</script>
